package com.songtech.position.service.impl;

import com.songtech.base.redis.RedisUtil;
import com.songtech.position.dao.PositionMapper;
import com.songtech.position.model.SysPosTrail;
import com.songtech.position.service.PositionService;
import com.songtech.server.Jedis.JedisBaseDao;
import com.songtech.server.constant.KeysConstant;
import com.songtech.server.entry.PositionProtocal;
import com.songtech.server.utils.GetKeysUtils;
import com.songtech.set.modle.TerminalInfo;
import com.songtech.set.service.SetService;
import com.songtech.set.service.TermianlInfoService;
import com.songtech.utils.ChangeUtil;
import com.songtech.utils.DateUtil;
import com.songtech.web.entry.Setting;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 定位service实现
 * @Author: rentie
 * @Date: 2018/4/11 11:09
 */
@Service
public class PositionServiceImpl implements PositionService {

    Logger logger = LoggerFactory.getLogger(PositionServiceImpl.class);
    /**
     * 命令拼接前缀
     */
    private final static String MAKER  = "*HQ";

    /**
     * 实时定位数据键值前缀
     */
    private final static String TERMINAL_POSITION_SHOW_KEY=KeysConstant.TERMINAL_POSITION_SHOW_KEY;


    /**
     * 已发送主动定位命令终端缓存键值前缀
     */
    private final static String ACTINVE_POSITION_PREFIX  = "activePosition:";

    /**
     * 命令分隔符
     */
    private final static String SP = ",";

    /**
     * redis操作对象
     *
     */
    @Autowired
    private JedisBaseDao jedisBaseDao;


    @Autowired
    private RedisUtil redisUtil;

    /**
     * 数据库操作对象，获取历史轨迹表信息
     */
    @Resource
    private PositionMapper positionMapper;

    @Autowired
    private TermianlInfoService termianlInfoService;

    @Autowired
    private SetService setService;

    /**
     * 主动定位
     *
     * @param imei 终端身份标识
     */
    @Override
    public void activePosition(String imei) {
        try {
            if (StringUtils.isNotEmpty(imei)) {
                String key = GetKeysUtils.combineAnyKeys(TERMINAL_POSITION_SHOW_KEY, imei);
                if (redisUtil.exists(key)) {
                    PositionProtocal protocal = (PositionProtocal) jedisBaseDao.get(key);
                    //判断是否在gps方式下进行主动定位
                    logger.info("current location type info " + protocal.getLocationType() + " unable send gps cmd");
                    Setting setting = setService.selectSettings(imei);
                    if (setting != null) {
                        if (!"lbs".equals(protocal.getLocationType()) && "0".equals(setting.getPostimeInterval())) {
                            String activePositionKey = ACTINVE_POSITION_PREFIX + imei;
                            StringBuffer sb = new StringBuffer(MAKER);
                            sb.append(SP);
                            sb.append(imei);
                            sb.append(SP);
                            sb.append("D2");
                            sb.append(SP);
                            sb.append(DateUtil.format(DateUtil.HOUR_MINUTE_SECOND));
                            sb.append(SP);
                            sb.append("0#");

                            //判断该imei是否曾经提交主动定位命令
                            if (redisUtil.exists(activePositionKey)) {
                                //当前时间
                                Long nowTime = DateUtil.getCurrentTimeSeconds();
                                //上次提交时间
                                Long lastTime = (Long) redisUtil.get(activePositionKey);
                                //时间间隔
                                Long interval = nowTime - lastTime;

                                //30秒内不做操作，30秒之后重新提交
                                if (interval >= 30) {
                                    jedisBaseDao.lpush(KeysConstant.SETTING, sb.toString());
                                    redisUtil.set(activePositionKey, nowTime);
                                }
                            } else { //未曾提交过，则提交一次，并保存提交时间到redis
                                jedisBaseDao.lpush(KeysConstant.SETTING, sb.toString());
                                redisUtil.set(activePositionKey, DateUtil.getCurrentTimeSeconds());
                            }
                        }
                    }
                }
            }
        }catch (Exception ex){
            logger.error("主动定位报错:" + ex);
        }
    }

    @Override
    public SysPosTrail queryRealTime(String imei) throws SQLException {
        String key="";
        if (StringUtils.isNotEmpty(imei)){
            key = GetKeysUtils.combineAnyKeys(TERMINAL_POSITION_SHOW_KEY,imei);
        }

        SysPosTrail bean=new SysPosTrail();
        /**
         * 判断redis缓存中是否有定位信息
         */
        if (redisUtil.exists(key)){
            /**
             * 有则取缓存到定位信息
             */
            PositionProtocal protocal = (PositionProtocal) jedisBaseDao.get(key);

            bean.setImei(protocal.getImei());
            bean.setDumpEnergy(protocal.getDumpEnergy());
            bean.setRecordTime(protocal.getRecordTime());
            bean.setLocationType(protocal.getLocationType());
            bean.setLatitude(protocal.getLatitude());
            bean.setLongitude(protocal.getLongitude());
            bean.setLatitudeFlag(protocal.getLatitudeFlag());
            bean.setManufacturer(protocal.getManufacturer());
            bean.setDirection(protocal.getDirection());
            bean.setSpeed(protocal.getSpeed());
        }else {
            /**
             * 若缓存中没有定位信息，则查询历史轨迹最新定位信息
             */
           bean = positionMapper.queryRealTime(imei);
        }
        if (bean == null){
            return bean;
        }

        /**
         * 根据imei获取设备信息
         */
        TerminalInfo termianlInfo = termianlInfoService.selectTerminalInfo(imei);
        if(termianlInfo!=null){
            if(StringUtils.isNotEmpty(termianlInfo.getTerminalNickname())){
                bean.setTerminalName(termianlInfo.getTerminalNickname());
            }else {
                bean.setTerminalName("未知设备");
            }

        }else{
            bean.setTerminalName("未知设备");
        }


        /**
         * 经纬度转换
         */
        Double longitude= ChangeUtil.LongToDouble(bean.getLongitude());
        Double latitude=ChangeUtil.LongToDouble(bean.getLatitude());

       /* double[] gps= ChangeUtil.gcj02ToBd09(longitude,latitude);*/
        bean.setLongitudeShow(longitude);
        bean.setLatitudeShow(latitude);


        return bean;

    }

    @Override
    public List<SysPosTrail> queryHistory(String startTime, String endTime,Integer locationType,String imei) throws SQLException {
        List<SysPosTrail> list = positionMapper.queryHistory(startTime,endTime,locationType,imei);
        if (list==null){
            return list;
        }
        /**
         * 根据imei获取设备信息
         */
        TerminalInfo termianlInfo = termianlInfoService.selectTerminalInfo(imei);
        String terminalName ="";
        if(termianlInfo!=null){
            if(StringUtils.isNotEmpty(termianlInfo.getTerminalNickname())){
                terminalName = termianlInfo.getTerminalNickname();
            }else {
                terminalName = "未知设备";
            }
        }else{
            terminalName = "未知设备";
        }


        for (SysPosTrail bean : list) {

            bean.setTerminalName(terminalName);

            /**
             * 经纬度转换
             */
            Double longitude= ChangeUtil.LongToDouble(bean.getLongitude());
            Double latitude=ChangeUtil.LongToDouble(bean.getLatitude());

            /* double[] gps= ChangeUtil.gcj02ToBd09(longitude,latitude);*/
            bean.setLongitudeShow(longitude);
            bean.setLatitudeShow(latitude);

        }

        return list;
    }
}
